<template>
  <div>
    <singer-listview :list="singers" :letter="letter"></singer-listview>
    <singer-Alphabet :list="singers" @change="handleLetterChange"></singer-Alphabet>
  </div>
</template>

<script>
import {ERR_OK} from 'api/config'
import axios from 'axios'
import SingerListview from './listview/Listview'
import SingerAlphabet from './Alphabet'

const HOT_NAME = '热门'
const HOT_SINGER_LEN = 10

export default {
  name: 'Singer',
  data () {
    return {
      singers: [],
      letter: ''
    }
  },
  components: {
    SingerListview,
    SingerAlphabet
  },
  created () {
    this.getSinger()
  },
  methods: {
    getSinger () {
      axios.get('/api/singer.json')
        .then(this.getSingerSucc)
    },
    getSingerSucc (res) {
      res = res.data
      if (res.data && res.code === ERR_OK) {
        this.singers = this.normalizeSinger(res.data.singerlist)
        console.log(this.singers)
      }
    },
    handleLetterChange (data) {
      this.letter = data
    },
    normalizeSinger (list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      list.forEach((item, index) => {
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(item)
        }

        let key = item.Findex
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(item)
      })

      let hot = []
      let ret = []
      for (let key in map) {
        let val = map[key]
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })

      return hot.concat(ret)
    }
  }
}

</script>
<style lang='stylus' scoped>

</style>
